package permission

import (
	"context"
	"strconv"

	"mall/service/backend/api/internal/logic/backend/util"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type PermissionListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPermissionListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PermissionListLogic {
	return &PermissionListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PermissionListLogic) PermissionList(req *types.PermissionListRequest) (resp *types.PermissionListResponse, err error) {
	logx.Infof("PermissionListRequest : %+v ", req)

	var page int64 = 1
	var pageSize int64
	var status int32
	if req.Current > 1 {
		page = req.Current
	}
	if req.PageSize > 0 { // 指定，检查最大值
		pageSize = req.PageSize
		if pageSize > l.svcCtx.Config.Query.MaxAmount {
			pageSize = l.svcCtx.Config.Query.MaxAmount
		}
	} else if req.PageSize == 0 { // 不指定，使用默认值
		pageSize = l.svcCtx.Config.Query.DefaultAmount
	} // 使用-1，rpc对应为0
	if req.Status != "" { // 不使用此字段为""，rpc对应为0
		if i, err := strconv.ParseInt(req.Status, 10, 32); err == nil {
			status = int32(i + 1)
		}
	}
	orderBys := util.ParseSorter(req.Sorter)
	filterBys := util.ParseFilter(req.Filter)
	res, err := l.svcCtx.BackendRpc.PermissionList(l.ctx, &backendclient.PermissionListRequest{
		Current:      page,
		PageSize:     pageSize,
		PermissionId: req.PermId,
		Name:         req.Name,
		Status:       status,
		OrderBy:      orderBys,
		FilterBy:     filterBys,
	})
	if err != nil {
		return nil, err
	}

	var list []*types.PermissionItem
	if len(res.List) > 0 {
		for _, item := range res.List {
			option := util.GetOptionByStatus(item.Status)
			list = append(list, &types.PermissionItem{
				Id:             item.Id,
				Name:           item.Name,
				Note:           item.Note,
				Status:         item.Status,
				StatusText:     util.GetStatusText(item.Status),
				DelStatus:      item.DelStatus,
				CreatedAt:      item.CreatedAt,
				CanDisable:     option.CanDisable,
				CanEnable:      option.CanEnable,
				CanForceDelete: option.CanForceDelete,
				CanRemove:      option.CanRemove,
				CanRestore:     option.CanRestore,
			})
		}
	}

	return &types.PermissionListResponse{
		Current:  page,
		PageSize: pageSize,
		List:     list,
		Total:    res.Total,
	}, nil
}
